package com.ricky.spring.demo.service.impl;

import com.google.common.collect.Lists;
import com.ricky.spring.demo.service.BroadcastService;
import com.ricky.spring.demo.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author leiruiqi {@literal <leiruiqi@baijiahulian.com>}
 **/
@Slf4j
@Service
public class BroadcastServiceImpl implements BroadcastService {

    Set<String> clientNameSet = new HashSet<>();

    @Resource
    private MessageService messageService;

    @Override
    public void addClient(String name) {
        clientNameSet.add(name);
    }

    @Override
    public void sendBroadCast(String msg) {
        List<Future<String>> list= Lists.newArrayList();
        for(String name:clientNameSet){
            Future<String> result = messageService.sendMsg(name,msg);
            list.add(result);

        }
        for(Future<String> result:list){
            try {
                String str = result.get(1000L, TimeUnit.SECONDS);
                log.info(str);
            } catch (InterruptedException e) {
                log.info("send fail");
            } catch (ExecutionException e) {
                log.info("send fail");
            } catch (TimeoutException e) {
                log.info("send fail");
            }
        }
        log.info("broadcast msg send finish:{}",msg);
    }
}
